import { BadGatewayException, Body, Controller, Get, Ip, Post, Query, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ModelType } from '@typegoose/typegoose/lib/types';
import { InjectModel } from 'nestjs-typegoose';
import { User } from 'src/decorator/user.decorator';
import { WebUserModel } from 'src/mongodb/models/userModel/webUser.models';
import { sign } from "jsonwebtoken";
import { addUserListDto, deleteUserDto, getUserListDto, setUserPassDto, updateUserDto } from './userDto/userDto';
import { searchCompanyDto } from '../companyApi/companyDto/companyDto';


@Controller('web')
export class UserController {

    constructor(@InjectModel(WebUserModel) private readonly webuserModel: ModelType<WebUserModel>) { }

    /**
     * @Description: 兼职后台登录
     * @param name {String} 账户
     * @param password {String}  密码
     * @return: Promise
     */
    @Post('login')
    @UseGuards(AuthGuard("local"))
    async weblogin(@User() user: WebUserModel, @Ip() ip: string) {
        try {
            const time = Math.floor(Date.now() / 1000)
            await this.webuserModel.updateOne({ name: user.name }, { logintime: time, loginip: ip.match(/\d+.\d+.\d+.\d+/)[0] })
            return {
                code: 200,
                data: user,
                token: await sign(
                    {
                        exp: time + (24 * 60 * 60),
                        data: user._id
                    }, '4N6UCQTNI0JFZ2UFYDDLLC4KNABC6L5VRH0K83A8UT')
            }
        } catch (error) {
            throw new BadGatewayException(error)
        }
    }



    /**
     * @Description: 添加后台用户
     * @param name {String} 账户
     * @param password {String}  密码
     * @return: Promise
     */
    @Post('addUserList')
    @UseGuards(AuthGuard("jwtweb"))
    async addUserList(@Body() body: addUserListDto, @Ip() ip: string) {
        try {
            const time = Math.floor(Date.now() / 1000)
            await this.webuserModel.create({
                name: body.name,
                password: body.password,
                logintime: time,
                regtime: time,
                loginip: ip.match(/\d+.\d+.\d+.\d+/)[0]
            })
            return { code: 200, message: '添加成功' }
        } catch (error) {
            throw new BadGatewayException(error)
        }

    }



    /**
     * @Description: 查询用户列表
     * @param pageNo {Number} 页码
     * @param pageSize {Number}  每页条数
     * @return: Promise
     */
    @Get('getUserList')
    @UseGuards(AuthGuard("jwtweb"))
    async getUserList(@Query() query: getUserListDto) {
        try {
            let data: { pageNo: number | string, pageSize: number | string } = query
            if (typeof data.pageNo == 'string') {
                data.pageNo = parseInt(data.pageNo)
            }
            if (typeof data.pageSize == 'string') {
                data.pageSize = parseInt(data.pageSize)
            }
            const total = await this.webuserModel.countDocuments()
            const userlist = await this.webuserModel.find().skip((data.pageNo - 1) * data.pageSize).limit(data.pageSize).sort({ '_id': -1 });
            return { total, data: userlist }

        } catch (error) {
            throw new BadGatewayException(error)
        }
    }




    /**
    * @Description: 搜索用户
    * @param name {Number} 账户
    * @return: Promise
    */
    @Get('searchGetUser')
    async searchCompany(@Query() query: searchCompanyDto) {
        try {
            const userlist = await this.webuserModel.find({ name: query.name })
            return { total: userlist.length, data: userlist }

        } catch (error) {
            throw new BadGatewayException(error)
        }
    }



    /**
    * @Description: 删除用户
    * @param id {String} 用户id
    * @return: Promise
    */
    @Post('deleteUser')
    @UseGuards(AuthGuard("jwtweb"))
    async deleteUser(@Body() body: deleteUserDto) {
        try {

            const webresult = await this.webuserModel.findById(body.id);
            if (webresult.name == 'admin') throw '不能删除admin用户';

            await this.webuserModel.deleteOne({ _id: body.id })
            return { code: 200, message: '删除成功' }

        } catch (error) {
            throw new BadGatewayException(error)
        }
    }



    /**
    * @Description: 修改用户状态
    * @param id {String} 用户id
    * @param status {String} 状态
    * @return: Promise
    */
    @Post('updateUser')
    @UseGuards(AuthGuard("jwtweb"))
    async updateUser(@Body() body: updateUserDto) {
        try {
            await this.webuserModel.updateOne({ _id: body.id }, { status: body.status })
            return { code: 200, message: '修改成功' }
        } catch (error) {
            throw new BadGatewayException(error)
        }
    }



    /**
    * @Description: 修改密码
    * @param name {String} 账号
    * @param password {String} 密码
    * @param setpassword {String} 修改的密码
    * @return: Promise
    */
    @Post('setUserPass')
    @UseGuards(AuthGuard("local"))
    async setUserPass(@Body() data: setUserPassDto, @User() user: WebUserModel) {
        try {
            const uppass = await this.webuserModel.updateOne({ _id: user._id }, { password: data.setpassword });
            if (uppass.nModified !== 1) throw '修改失败';

            return { code: 200, message: "修改成功" };
        } catch (error) {
            throw new BadGatewayException(error);
        };
    }



}
